package com.github.xzb617.client.config;

import com.github.xzb617.client.config.key.ClientKeyType;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Map;
import java.util.Set;

/**
 * 客户端下发器
 * <p>功能是下发消息给客户端</p>
 * @author xzb617
 */
@Component("clientsTransmitter")
public class ClientsTransmitter {

    private final ClientsContainer clientsContainer;
    private final static Boolean RESP_BODY = Boolean.TRUE;

    public ClientsTransmitter(ClientsContainer clientsContainer) {
        this.clientsContainer = clientsContainer;
    }

    /**
     * 通知某个实例
     * @param clientKey 客户端标识
     * @param instanceKey 实例标识
     */
    public void transmitInstance(String clientKey, String instanceKey) {
        DeferredResult instance = this.clientsContainer.getInstance(clientKey, instanceKey);
        if (instance != null) {
            instance.setResult(ResponseEntity.status(HttpStatus.OK).body(RESP_BODY));
        }
    }

    /**
     * 通知指定的多个实例
     * @param clientKey 客户端标识
     * @param instanceKeys 实例标识数组
     */
    public void transmitInstances(String clientKey, Set<String> instanceKeys) {
        for (String instanceKey : instanceKeys) {
            this.transmitInstance(clientKey, instanceKey);
        }
    }

    /**
     * A:B&C A:B&*
     *
     * 通知客户端下的所有实例
     * @param clientKey 客户端标识
     */
    public void transmitClient(ClientKeyType clientKeyType, String clientKey) {
        Map<String, Map<String, DeferredResult>> clientsMap = this.clientsContainer.getClient(clientKeyType, clientKey);
        if (clientsMap!=null && !clientsMap.isEmpty()) {
            Set<Map.Entry<String, Map<String, DeferredResult>>> entries = clientsMap.entrySet();
            for (Map.Entry<String, Map<String, DeferredResult>> entry : entries) {
                Set<String> instanceKeys = entry.getValue().keySet();
                this.transmitInstances(entry.getKey(), instanceKeys);
            }
        }
    }
}
